import { Component, OnInit } from '@angular/core'
import { ActivationEnd, Router } from '@angular/router'
import { filter } from 'rxjs'
import { Menu } from 'src/app/@core/interface/home'
import * as _ from 'lodash'
import { select, Store } from '@ngrx/store'
import { AppState, AvatarState } from 'src/app/store'
import { UserAuthService } from 'src/app/@core/user-auth.service'
import { CookieService } from 'ngx-cookie-service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.less']
})
export class HeaderComponent implements OnInit {
  navType: number = 2
  navTitle: string = '首页'
  _navList: Array<Menu>
  get navList() {
    return this._navList
  }

  set navList(val: Array<Menu>) {
    this._navList = val
    if (!_.isEqual(this._navList, val)) this.navListChange()
  }

  TOKEN = this.cookieService.get('token')

  constructor(
    private router: Router,
    private store: Store<AppState>,
    private storeAvatar: Store<AvatarState>,
    public userAuthService: UserAuthService,
    public cookieService: CookieService
  ) {
    let streamto = store.pipe(select('todos'))
    streamto.subscribe((res) => {
      this.navList = res
    })

    let avatar = storeAvatar.pipe(select('avatar'))
    avatar.subscribe((res) => {
      if (res)
        this.imgsrc = res
      else
        this.imgsrc = "../assets/img/default.png"
    })

    this.router.events
      .pipe(
        filter((event: any) => {
          return event instanceof ActivationEnd
        })
      )
      .subscribe((event: any) => {
        if (event.snapshot.data.navType) {
          this.navType = event.snapshot.data.navType
          if (this.navType === 2) {
            this.navTitle = event.snapshot.data.navTitle
          }
        } else {
          this.navType = 1
        }
      })
  }

  imgsrc = "../assets/img/default.png"
  userId = parseInt(localStorage.getItem('userId'))

  ngOnInit(): void {
    if (this.userId) {
      this.getAvatar()
    }
    this.addmenus()
    if (
      this.userAuthService.userInfo.role &&
      this.userAuthService.userInfo.role === 'admin'
    ) {
      this.navList.push({
        name: '设置',
        value: 4,
        link: '/manage/collection',
        img: '../assets/img/home/setting.svg'
      })
    }
  }

  getAvatar() {
    if (this.cookieService.get('token')) {
      this.userAuthService.getAvatar(this.userId).subscribe((res) => {
        this.store.dispatch({
          type: 'AVATAR',
          payload: res.data.FileUrl
        })
      })
    }
  }

  addmenus() {
    if (this.cookieService.get('token')) {
      this.navList = []
      if (localStorage.getItem('IS_SHARED')) {
        this.navList.push({
          name: '区块链',
          value: 2,
          link: '/blockchain',
          img: '../assets/img/home/blockchain.svg'
        })
      }
    }
  }

  navListChange() {
    setTimeout(() => {
      this.navList = _.sortBy(this.navList, function (o: Menu) {
        return o.value
      })
    })
  }

  gotoPage(route) {
    this.router.navigate([route])
  }

  logOut() {
    this.router.navigate(['/login/logins'])
    this.userAuthService.userLogOut().subscribe((res) => {
      if (res.code === 0) {
        this.cookieService.delete('token')
        localStorage.removeItem('token')
        localStorage.removeItem('userName')
        localStorage.removeItem('ROLE')
        localStorage.removeItem('userId')
        localStorage.removeItem('PasswordChange')
        this.userAuthService.userInfo.userName = null
        this.store.dispatch({
          type: 'RESET_TODO',
          payload: {}
        })
      }
    })
  }

  goBaseInfo() {
    this.router.navigate(['/baseUserInfo'])
  }

  setTracingPoint() {
    ; (window as any).onEvent('页面跳转', 'click', '页面跳转', '')
  }
}
